package com.tools.modules.monitor;

import com.tools.common.beans.constant.ControllerConstant;
import com.tools.common.beans.vo.Result;
import com.tools.controller.BaseController;
import com.tools.monitor.redis.RedisConvert;
import com.tools.monitor.redis.RedisMonitorVo;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * Redis 控制层
 * @Author : ShangJY
 * @create 2024/6/15 22:04
 */
@RestController
@RequestMapping(ControllerConstant.API_MONITOR_PREFIX )
public class RedisController extends BaseController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 基础路径
     */
    private final String prefix = "monitor/";

    @GetMapping(value = {"redis","redis.html"})
    public ModelAndView monitor() {
        return jumpPage(prefix + "redis"+"/redis");
    }

    @GetMapping("/redis/get-monitor-info")
    public Result<RedisMonitorVo> getRedisMonitorInfo() {
        // 获得 Redis 统计信息
        Properties info = stringRedisTemplate.execute((RedisCallback<Properties>) RedisServerCommands::info);
        Long dbSize = stringRedisTemplate.execute(RedisServerCommands::dbSize);
        Properties commandStats = stringRedisTemplate.execute((RedisCallback<Properties>) connection ->{
            return  connection.info("commandstats");
        });
        assert commandStats != null;
        return Result.OK(RedisConvert.build(info,dbSize,commandStats));
    }
}
